package com.huwaiwai.nio.demo06;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;

/**
 * Java NIO 管道是2个线程之间的单向数据连接。
 * Pipe有一个source通道和一个sink通道。
 * 数据会被写到sink通道，从source通道读取。
 * Created by huweiwei on 2017/4/21.
 */
public class PipeDemo {

    public static void main(String [] args) throws IOException {
        Pipe pipe = Pipe.open();

        Pipe.SinkChannel sinkChannel = pipe.sink();
        Pipe.SourceChannel sourceChannel = pipe.source();

        String newData = "New String to write to file..." + System.currentTimeMillis();
        System.out.println(newData);
        ByteBuffer writeBuf = ByteBuffer.allocate(48);
        writeBuf.clear();
        writeBuf.put(newData.getBytes());
        writeBuf.flip();

        while (writeBuf.hasRemaining()) {
            sinkChannel.write(writeBuf);
        }
        ByteBuffer readBuf = ByteBuffer.allocate(48);
        int bytesRead = sourceChannel.read(readBuf);

        readBuf.flip();
        while (readBuf.hasRemaining()) {
            System.out.print((char) (readBuf.get()));
        }
        sinkChannel.close();
        sourceChannel.close();

    }


}
